<template>
	<view class="order-container">
		<!-- 订单状态切换栏 -->
		<view class="status-tabs">
			<view 
				v-for="(tab, index) in statusTabs" 
				:key="index"
				:class="['tab-item', currentStatus === tab.value ? 'active' : '']"
				@tap="switchStatus(tab.value)"
			>
				{{tab.label}}
			</view>
		</view>
		
		<!-- 订单列表 -->
		<scroll-view 
			scroll-y 
			class="order-list" 
			@scrolltolower="loadMore"
			refresher-enabled="true"
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<!-- 加载状态 -->
			<view v-if="loading && orders.length === 0" class="loading-container">
				<text class="loading-text">加载中...</text>
			</view>
			
			<!-- 空状态 -->
			<view v-else-if="!loading && orders.length === 0" class="empty-container">
				<text class="empty-text">暂无订单</text>
			</view>
			
			<!-- 订单列表 -->
			<view v-else>
				<view v-for="(order, index) in filteredOrders" :key="index" class="order-item">
					<view class="order-header">
						<view class="order-left">
							<text class="car-type">{{order.carType}}</text>
							<text :class="['order-status', order.status]">{{getStatusText(order.status)}}</text>
						</view>
						<text class="order-price">¥{{order.price}}</text>
					</view>
					
					<view class="route-info">
						<view class="location-item">
							<view class="location-dot start"></view>
							<text class="location-text">{{order.startLocation}}</text>
						</view>
						<view class="location-line"></view>
						<view class="location-item">
							<view class="location-dot end"></view>
							<text class="location-text">{{order.endLocation}}</text>
						</view>
					</view>
					
					<view class="order-footer">
						<view class="order-info">
							<text class="order-no">订单号：{{order.orderNo}}</text>
							<text class="order-time">{{order.createTime}}</text>
						</view>
						<view class="btn-group">
							<button 
								v-if="order.status === 'pending_payment'" 
								class="btn-pay" 
								@tap="handlePay(order)"
							>立即支付</button>
							<button 
								v-if="order.status === 'pending_travel'" 
								class="btn-cancel" 
								@tap="handleCancel(order)"
							>取消订单</button>
							<button 
								v-if="order.status === 'completed' || order.status === 'cancelled'"
								class="btn-delete" 
								@tap="handleDelete(order, index)"
							>删除订单</button>
						</view>
					</view>
				</view>
				<!-- 加载更多状态 -->
				<view v-if="loading && hasMore" class="loading-more">
					<text>加载中...</text>
				</view>

				<!-- 没有更多数据状态 -->
				<view v-else-if="!loading && !hasMore" class="no-more">
					<text>没有更多数据了</text>
				</view>
			</view>
		</scroll-view>
		<!-- 使用底部导航组件 -->
		<!-- <bottom-nav :nav-list="bottomNavList" @nav-change="handleNavChange"></bottom-nav> -->
	</view>
</template>

<script>
	import BottomNav from '@/components/BottomNav/BottomNav.vue'
	import userOrder from '@/api/order.js'
	
	export default {
		components: {
			BottomNav
		},
		data() {
			return {
				currentStatus: 'all',
				statusTabs: [
					{ label: '全部', value: 'all' },
					{ label: '待支付', value: 'pending_payment' },
					{ label: '待出行', value: 'pending_travel' },
					{ label: '已完成', value: 'completed' },
					{ label: '已取消', value: 'cancelled' }
				],
				orders: [],
				hasMore: true,
				page: 1,
				pageSize: 10,
				loading: false, // 添加加载状态
				refreshing: false, // 下拉刷新状态
				// 底部导航数据
				// bottomNavList: [
				// 	{ text: '首页', path: '/pages/firstPage/firstPage' },
				// 	{ text: '优惠卷', path: '/pages/couponCenter/couponCenter' },
				// 	{ text: '订单', path: '/pages/userOrder/userOrder' },
				// 	{ text: '我的', path: '/pages/mySelf/mySelf' },
				// ],
			}
		},
		// 添加生命周期方法
		onLoad() {
			this.initData();
		},
		onShow() {
			// 只在需要时刷新数据，避免无限刷新
			if (this.orders.length === 0) {
				this.initData();
			}
		},
		computed: {
			filteredOrders() {
				if (this.currentStatus === 'all') {
					return this.orders;
				}
				return this.orders.filter(order => order.status === this.currentStatus);
			}
		},
		methods: {
			// 初始化数据
			async initData() {
				try {
					this.loading = true;
					await this.getOrderList();
				} catch (error) {
					console.error('初始化数据失败:', error);
					uni.showToast({ 
						title: '数据加载失败', 
						icon: 'error' 
					});
				} finally {
					this.loading = false;
				}
			},
			// 处理底部导航切换
			handleNavChange(index) {
				console.log(index, "1233");
			
				const list = this.bottomNavList;
			
				if (!Array.isArray(list)) {
					console.error('bottomNavList 不是数组');
					return;
				}
			
				if (index == null || isNaN(index) || index < 0 || index >= list.length) {
					console.error('无效的索引:', index);
					return;
				}
			
				const item = list[index];
				if (!item || !item.path) {
					console.error('无效的导航项:', item);
					return;
				}
			
				const targetPath = item.path;
				if (targetPath !== this.$route?.path) {
					uni.navigateTo({
						url: targetPath,
						success: () => {
							console.log('底部导航跳转成功:', targetPath);
						},
						fail: (err) => {
							console.error('底部导航跳转失败:', targetPath, err);
							uni.showToast({
								title: '跳转失败',
								icon: 'none'
							});
						}
					});
				}
			},
			//路由跳转
			goToPath(url) {
			  // 参数校验
			  if (!url || typeof url !== 'string') {
			    console.error('路由跳转失败：url参数为空或类型错误', url);
			    uni.showToast({
			      title: '跳转路径错误',
			      icon: 'none'
			    });
			    return;
			  }
			  
			  // 执行路由跳转
			  uni.navigateTo({
			    url,
			    success: () => {
			      console.log('路由跳转成功:', url);
			    },
			    fail: (err) => {
			      console.error('路由跳转失败:', url, err);
			      uni.showToast({
			        title: '跳转失败，请稍后再试',
			        icon: 'none'
			      });
			    },
			    complete: () => {
			      // 跳转完成后的通用处理
			    }
			  });
			},
			// 加载更多数据
			async loadMore() {
				if (!this.hasMore || this.loading) return;
				
				try {
					this.loading = true;
					// 这里添加实际的加载更多逻辑
					await new Promise(resolve => setTimeout(resolve, 1000));
					if(this.currentStatus==='all'){
						await this.getOrderList();
					}else if(this.currentStatus==='pending_payment'){
						await this.toBePaid();
					}else if(this.currentStatus==='pending_travel'){
						await this.toBeOut();
					}else if(this.currentStatus==='completed'){
						await this.completed();
					}else if(this.currentStatus==='cancelled'){
						await this.cancelled();
					}
				} catch (error) {
					console.error('加载更多失败:', error);
					uni.showToast({ title: '加载失败', icon: 'error' });
				} finally {
					this.loading = false;
				}
			},
			// 切换状态
			async switchStatus(status) {
				if (this.loading) return; // 防止重复请求
				
				this.currentStatus = status;
				this.page = 1;
				this.hasMore = true;
				this.orders = []; // 清空当前数据
				
				try {
					this.loading = true;
					
					// 根据状态加载对应数据
					switch(status) {
						case 'all':
							await this.getOrderList();
							break;
						case 'pending_payment':
							await this.toBePaid();
							break;
						case 'pending_travel':
							await this.toBeOut();
							break;
						case 'completed':
							await this.completed();
							break;
						case 'cancelled':
							await this.cancelled();
							break;
						default:
							await this.getOrderList();
					}
				} catch (error) {
					console.error('切换状态失败:', error);
					uni.showToast({ 
						title: '数据加载失败', 
						icon: 'error' 
					});
				} finally {
					this.loading = false;
				}
			},
			// 统一的数据映射方法
			mapOrderData(order) {
				let status = 'unknown';
				const statusCode = order.orderStatus;
				const payState = order.orderState;

				// 精准状态组合判断
				if (statusCode === 3 && payState === 0) {
					// 未支付且未出行
					status = 'pending_payment';
				} else if (statusCode === 4) {
					// 已取消
					status = 'cancelled';
				} else if ((statusCode === 0 || statusCode === 1 || statusCode === 2) && payState === 0) {
					// 未支付且进行中
					status = 'pending_travel';
				} else if (statusCode === 3 && payState === 1) {
					// 已完成且已支付
					status = 'completed';
				}
				return {
					orderNo: order.orderId || order.orderNo || '',
					status,
					orderState: order.orderState,
					orderStatus: order.orderStatus,
					carType: order.modelName || order.carType || '未知车型',
					price: order.price || 0,
					startLocation: order.startAddress || order.startLocation || '未知起点',
					endLocation: order.endAddress || order.endLocation || '未知终点',
					createTime: order.createTime || order.createDate || ''
				};
			},
			//全部订单
			async getOrderList(){
				try {
					//获取用户信息
					const user = uni.getStorageSync('user');
					if (!user || !user.userId) {
						throw new Error('用户信息不存在');
					}
					
					console.log('获取全部订单，用户ID:', user.userId);
					const res = await userOrder.getOrderList(user.userId);	
					console.log('全部订单响应:', res);
					
					if (res && Array.isArray(res)) {
						this.orders = res.map(order => this.mapOrderData(order));
					} else {
						this.orders = [];
					}
				} catch (error) {
					console.error('获取全部订单失败:', error);
					this.orders = [];
					const errorMessage = error.message || '获取全部订单失败';
					uni.showToast({ 
						title: errorMessage, 
						icon: 'error' 
					});
					throw error;
				}
			},
			//待支付订单
			async toBePaid(){
				try {
					//获取用户信息
					const user = uni.getStorageSync('user');	
					if (!user ||!user.userId) {
						throw new Error('用户信息不存在');	
					}
					console.log('获取待支付订单，用户ID:', user.userId);
					const res = await userOrder.toBePaidList(user.userId);
					console.log('待支付订单响应:', res);
					if (res && Array.isArray(res)) {
						this.orders = res.map(order => this.mapOrderData(order));	
						console.log('待支付订单映射后:', this.orders);
					}else {
						this.orders = [];
					}
				}
				catch (error) {
					console.error('获取待支付订单失败:', error);
					this.orders = [];
					const errorMessage = error.message || '获取待支付订单失败';	
					uni.showToast({ 
						title: errorMessage, 
						icon: 'error' 
					});
					throw error;
				}
			},
			// 待出行订单
			async toBeOut(){
				try {
					//获取用户信息
					const user = uni.getStorageSync('user');	
					if (!user ||!user.userId) {
						throw new Error('用户信息不存在');	
					}
					console.log('获取待出行订单，用户ID:', user.userId);
					const res = await userOrder.toBeOutList(user.userId);
					console.log('待出行订单响应:', res);
					if (res && Array.isArray(res)) {
						this.orders = res.map(order => this.mapOrderData(order));		
					}else {
						this.orders = [];	
					}
				}
				catch (error) {
					console.error('获取待出行订单失败:', error);
					this.orders = [];
					const errorMessage = error.message || '获取待出行订单失败';	
					uni.showToast({ 
						title: errorMessage, 
						icon: 'error' 
					});
					throw error;
				}
			},
			// 已完成订单
			async completed(){
				try {
					//获取用户信息
					const user = uni.getStorageSync('user');
					if (!user || !user.userId) {
						throw new Error('用户信息不存在');
					}
					
					console.log('获取已完成订单，用户ID:', user.userId);
					const res = await userOrder.completedList(user.userId);	
					console.log('已完成订单响应:', res);
					
					if (res && Array.isArray(res)) {
						this.orders = res.map(order => this.mapOrderData(order));
					} else {
						this.orders = [];
					}
				} catch (error) {
					console.error('获取已完成订单失败:', error);
					this.orders = [];
					const errorMessage = error.message || '获取已完成订单失败';
					uni.showToast({ 
						title: errorMessage, 
						icon: 'error' 
					});
					throw error;
				}
			},
			// 已取消订单
			async cancelled(){
				try {
					//获取用户信息
					const user = uni.getStorageSync('user');
					if (!user || !user.userId) {
						throw new Error('用户信息不存在');
					}
					
					console.log('获取已取消订单，用户ID:', user.userId);
					const res = await userOrder.cancelledList(user.userId);	
					console.log('已取消订单响应:', res);
					
					if (res && Array.isArray(res)) {
						this.orders = res.map(order => this.mapOrderData(order));
					} else {
						this.orders = [];
					}
				} catch (error) {
					console.error('获取已取消订单失败:', error);
					this.orders = [];
					const errorMessage = error.message || '获取已取消订单失败';
					uni.showToast({ 
						title: errorMessage || '取消订单失败', 
						icon: 'error' 
					});
					throw error;
				}
			},
			getStatusText(status) {
				const statusMap = {
					'pending_payment': '待支付',
					'pending_travel': '待出行',
					'completed': '已完成',
					'cancelled': '已取消',
					// 添加 orderState 的文本映射
					0: '待支付',
					1: '已支付'
				};
				return statusMap[status] || status;
			},
			// 删除订单
			async handleDelete(order) {
				console.log('删除订单:', order);
				try {
					const res = await uni.showModal({
						title: '提示',
						content: '确定要删除该订单吗？',
						confirmColor: '#ff4d4f'
					});
					
					if (!res.confirm) return;
					
					uni.showLoading({ title: '正在删除...' });
					// 这里添加实际的删除逻辑
					console.log('删除订单111:', order);
					const orderRes = await userOrder.deleteOrder(order.orderNo);
					console.log(orderRes);
					if(orderRes){
						uni.showToast({ title: orderRes, icon: 'error' });
						return;
					}
					await new Promise(resolve => setTimeout(resolve, 1000));
				} catch (error) {
					uni.hideLoading();
					uni.showToast({ 
						title: error || '删除失败', 
						icon: 'error',
						duration: 2000
					});
				}
			},
			async handlePay(order) {
				try {
					uni.showLoading({ title: '正在支付...' });
					// 这里添加实际的支付逻辑
					await new Promise(resolve => setTimeout(resolve, 1500));
					uni.hideLoading();
					uni.showToast({ title: '支付成功', icon: 'success' });
					order.status = 'pending_travel';
				} catch (error) {
					uni.showToast({ title: '支付失败', icon: 'error' });
				}
			},
			async handleCancel(order) {
				console.log('取消订单:', order);
				try {
					// 显示确认框
					const res = await uni.showModal({
						title: '提示',
						content: '确定要取消该订单吗？',
						confirmColor: '#ff4d4f'
					});

					if (!res.confirm) return;
					
					uni.showLoading({ title: '正在取消...' });
					// 这里添加实际的取消逻辑
					console.log('取消订单111:', order);
					const orderRes = await userOrder.cancelOrder(order);
					console.log(orderRes);
					if(orderRes){
						 // 打印错误信息
   						console.error('取消订单接口返回错误:', orderRes); 
						uni.showToast({ title: orderRes, icon: 'error' });
						return;
					}

					await new Promise(resolve => setTimeout(resolve, 1000));
					uni.hideLoading();
					uni.showToast({ title: '取消成功', icon: 'success' });
					order.status = 'cancelled';
				} catch (error) {
					// 打印具体错误信息
					console.error('取消订单出错:', error); 
					uni.hideLoading();
					uni.showToast({ title: error, icon: 'error' });
				}
			},
			// 下拉刷新
			async onRefresh() {
				this.refreshing = true;
				// 这里添加实际的刷新逻辑
				console.log('开始刷新...',this.currentStatus);
				await new Promise(resolve => setTimeout(resolve, 1000));
				// await this.initData();
				if(this.currentStatus==='all'){
					await this.getOrderList();
				}else if(this.currentStatus==='pending_payment'){
					await this.toBePaid();
				}else if(this.currentStatus==='pending_travel'){
					await this.toBeOut();
				}else if(this.currentStatus==='completed'){
					await this.completed();
				}else if(this.currentStatus==='cancelled'){
					await this.cancelled();
				}
				this.refreshing = false;
			}
		}
	}
</script>

<style>
.order-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding: 0 20rpx;
}

.status-tabs {
	display: flex;
	background-color: #ffffff;
	padding: 20rpx;
	position: sticky;
	top: 0;
	z-index: 100;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	margin: 0 -20rpx;
}

.tab-item {
	flex: 1;
	text-align: center;
	font-size: 28rpx;
	color: #666;
	padding: 10rpx 0;
	position: relative;
}

.tab-item.active {
	color: #007AFF;
	font-weight: bold;
}

.tab-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 40rpx;
	height: 4rpx;
	background-color: #007AFF;
}

.order-list {
	height: calc(100vh - 200rpx); /* 减去顶部状态栏和底部导航栏的高度 */
	padding: 20rpx 0;
	padding-bottom: 120rpx; /* 为底部导航栏留出空间 */
}

.order-item {
	background-color: #ffffff;
	padding: 24rpx;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.order-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24rpx;
}

.order-left {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.car-type {
	font-size: 32rpx;
	color: #333;
	font-weight: bold;
}

.order-status {
	font-size: 26rpx;
	padding: 4rpx 12rpx;
	border-radius: 20rpx;
}

.order-status.pending_payment {
	color: #ff6b6b;
	background-color: #fff1f0;
}

.order-status.pending_travel {
	color: #4CAF50;
	background-color: #f6ffed;
}

.order-status.completed {
	color: #999;
	background-color: #f5f5f5;
}

.order-status.cancelled {
	color: #999;
	background-color: #f5f5f5;
}

.order-price {
	font-size: 36rpx;
	color: #ff6b6b;
	font-weight: bold;
}

.route-info {
	padding: 24rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	margin-bottom: 24rpx;
	position: relative;
}

.location-item {
	display: flex;
	align-items: center;
	margin-bottom: 24rpx;
}

.location-item:last-child {
	margin-bottom: 0;
}

.location-dot {
	width: 16rpx;
	height: 16rpx;
	border-radius: 50%;
	margin-right: 20rpx;
	flex-shrink: 0;
}

.location-dot.start {
	background-color: #4CAF50;
}

.location-dot.end {
	background-color: #ff6b6b;
}

.location-line {
	position: absolute;
	left: 15rpx;
	top: 40rpx;
	bottom: 40rpx;
	width: 2rpx;
	background-color: #ddd;
}

.location-text {
	font-size: 28rpx;
	color: #333;
	flex: 1;
}

.order-footer {
	display: flex;
	justify-content: space-between;
	align-items: flex-end;
}

.order-info {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.order-no {
	font-size: 24rpx;
	color: #999;
}

.order-time {
	font-size: 24rpx;
	color: #999;
}

.btn-group {
	display: flex;
	gap: 16rpx;
}

.btn-pay, .btn-cancel, .btn-delete {
	margin: 0;
	font-size: 26rpx;
	padding: 12rpx 32rpx;
	border-radius: 30rpx;
	line-height: 1.5;
}

.btn-pay {
	background-color: #007AFF;
	color: #ffffff;
}

.btn-cancel {
	background-color: #f5f5f5;
	color: #666;
	border: 1rpx solid #ddd;
}

.btn-delete {
	background-color: #ff4d4f;
	color: #ffffff;
}

/* 添加按钮点击效果 */
.btn-pay:active, .btn-cancel:active, .btn-delete:active {
	opacity: 0.8;
}

.loading-more, .no-more {
	text-align: center;
	padding: 20rpx 0;
	color: #999;
	font-size: 24rpx;
}

/* 添加一些动画效果 */
.order-item {
	animation: slideIn 0.3s ease;
}

@keyframes slideIn {
	from {
		opacity: 0;
		transform: translateY(20rpx);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}
/* 固定底部菜单样式 */
	.bottom-menu {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx; /* 根据实际图标和文本大小调整 */
		background-color: #fff;
		display: flex;
		justify-content: space-around;
		align-items: center;
		border-top: 1rpx solid #eee;
		z-index: 100; /* 确保菜单在最上层 */
	}

	.bottom-menu .menu-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.bottom-menu .menu-icon {
		width: 40rpx; /* 根据实际图标大小调整 */
		height: 40rpx; /* 根据实际图标大小调整 */
		margin-bottom: 4rpx;
	}

	.bottom-menu .menu-text {
		font-size: 24rpx;
		color: #333;
	}

	.loading-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
	}

	.loading-text {
		font-size: 28rpx;
		color: #666;
	}

	.empty-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
</style>
